package Volume2.ch1;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * 8.收集结构
 * @Auther jacob
 * @Date 2020/8/9 23:07
 */
public class CollectionResults {

    public static final String VOWEL_SET = "[aeiouAEIOU]";

    public static Stream<String> noVowels() throws IOException {
        String contents = new String(Files.readAllBytes(
                Paths.get("src/Volume2/ch1/words.txt")), StandardCharsets.UTF_8);
        List<String> words = Arrays.asList(contents.split("\n"));

        return words.stream().map(s -> s.replaceAll(VOWEL_SET, ""));
    }

    public static <T> void show(String label, Set<T> set){
        System.out.print(label + ": " + set.getClass().getName());
        System.out.println("["
                + set.stream().limit(10).map(Objects::toString).collect(Collectors.joining(","))
                + "]");
    }

    public static void main(String[] args) throws IOException {
        // 获取当前流中的迭代器
        Iterator<Integer> iter = Stream.iterate(0, n -> n + 1).limit(10).iterator();
        while (iter.hasNext()){
            System.out.println(iter.next());
        }

        // 将流转为数组
        Object[] numbers = Stream.iterate(0, n -> n + 1).limit(10).toArray();
        System.out.println("Object array(这一个Object类型的数组): " + numbers);

        // 不同通过强制转换经Object数组转化为Integer数组
        try{
            Integer number = (Integer)numbers[0];
            System.out.println("number: " + number);
            System.out.println("以下转换方法会抛出异常：");
            Integer[] numbers2 = (Integer[]) numbers;

        } catch (ClassCastException e){
            System.out.println(e);
        }

        // 生成Integer数组的正确方式
        Integer[] integers = Stream.iterate(0, n -> n + 1).limit(10).toArray(Integer[]::new);
        System.out.println("Integer array(这一个Integer类型的数组): " + integers);

        // 获取没有元音字符的set
        Set<String> noVowelSet = noVowels().collect(Collectors.toSet());
        show("noVowelSet", noVowelSet);

        // 获取没有元音字符的TreeSet
        TreeSet<String> noVowelsTreeSet = noVowels().collect(Collectors.toCollection(TreeSet::new));
        show("noVowelsTreeSet", noVowelsTreeSet);

        // 流中字符串拼接
        String noVowelString = noVowels().collect(Collectors.joining(", "));
        System.out.println("noVowelString: " + noVowelString);

        IntSummaryStatistics summary = noVowels().collect(Collectors.summarizingInt(String::length));
        double average = summary.getAverage();
        int max = summary.getMax();
        System.out.println("Average word length: " + average);
        System.out.println("Max word length: " + max);
        System.out.println("forEach:");
        noVowels().limit(10).forEach(System.out::println);
    }
}
